package com.dhq.myapp.ui.identity

import android.util.Log
import com.rokid.cxr.client.extend.CxrApi
import com.rokid.cxr.client.extend.callbacks.SendStatusCallback
import com.rokid.cxr.client.utils.ValueUtil

/**
 * DESC 语音命令执行
 * Created by DHQ on 2025/10/31.
 */
class RokidVoiceCommandExecutor(
    private val onCommandExecuted: ((success: Boolean, feedback: String) -> Unit)? = null
) {
    private val TAG = "RokidCommandExecutor"
    // 提词器默认文本（Base64编码，实际需根据需求生成）
    private val DEFAULT_WORD_TIPS_TEXT = "欢迎使用Rokid眼镜语音协同功能".toByteArray()
    // 提词器文件名（用于SDK识别数据类型）
    private val WORD_TIPS_FILE_NAME = "welcome_tips.txt"

    /**
     * 解析ASR结果并执行对应指令
     */
    fun executeCommand(asrText: String) {
        // 1. 检查蓝牙连接状态
        if (!CxrApi.getInstance().isBluetoothConnected) {
            val feedback = "蓝牙未连接，无法执行指令"
            onCommandExecuted?.invoke(false, feedback)
            sendTtsFeedback(feedback)
            return
        }

        // 2. 语义解析：提取指令类型（实际需用NLP优化，此处简化匹配）
        when {
            asrText.contains("打开提词器") -> {
                executeOpenWordTips(asrText)
            }
            asrText.contains("设置亮度") -> {
                // 提取亮度值（如“设置亮度为10”）
                val brightness = extractBrightness(asrText)
                if (brightness != null) {
                    executeSetBrightness(brightness)
                } else {
                    val feedback = "未识别到亮度值，请重新指令"
                    onCommandExecuted?.invoke(false, feedback)
                    sendTtsFeedback(feedback)
                }
            }
            asrText.contains("关闭提词器") -> {
                executeCloseWordTips()
            }
            asrText.contains("拍照") -> {
                executeTakePhoto()
            }
            else -> {
            val feedback = "未识别指令：$asrText"
            onCommandExecuted?.invoke(false, feedback)
            sendTtsFeedback(feedback)
        }
        }
    }

    /**
     * 执行“打开提词器”指令
     */
    private fun executeOpenWordTips(asrText: String) {
        // 步骤1：打开提词器场景
        val openStatus = CxrApi.getInstance().controlScene(
            ValueUtil.CxrSceneType.WORD_TIPS,
            true,
            null
        )
        if (openStatus != ValueUtil.CxrStatus.REQUEST_SUCCEED) {
            val feedback = "打开提词器失败，状态：$openStatus"
            onCommandExecuted?.invoke(false, feedback)
            sendTtsFeedback(feedback)
            return
        }

        // 步骤2：发送提词器文本（如从ASR中提取自定义文本，此处用默认文本）
        val sendStatus = CxrApi.getInstance().sendStream(
            ValueUtil.CxrStreamType.WORD_TIPS,
            DEFAULT_WORD_TIPS_TEXT,
            WORD_TIPS_FILE_NAME,
            object : SendStatusCallback {
                override fun onSendSucceed() {
                    val feedback = "提词器已打开，显示欢迎文本"
                    onCommandExecuted?.invoke(true, feedback)
                    sendTtsFeedback(feedback)
                }

                override fun onSendFailed(errorCode: ValueUtil.CxrSendErrorCode?) {
                    val feedback = "提词器文本发送失败，错误码：$errorCode"
                    onCommandExecuted?.invoke(false, feedback)
                    sendTtsFeedback(feedback)
                }
            }
        )
        if (sendStatus != ValueUtil.CxrStatus.REQUEST_SUCCEED) {
            val feedback = "提词器文本发送请求失败，状态：$sendStatus"
            onCommandExecuted?.invoke(false, feedback)
            sendTtsFeedback(feedback)
        }
    }

    /**
     * 执行“设置亮度”指令（亮度范围0-15）
     */
    private fun executeSetBrightness(brightness: Int) {
        if (brightness < 0 || brightness > 15) {
            val feedback = "亮度值需在0-15之间，当前值：$brightness"
            onCommandExecuted?.invoke(false, feedback)
            sendTtsFeedback(feedback)
            return
        }

        val status = CxrApi.getInstance().setGlassBrightness(brightness)
        if (status == ValueUtil.CxrStatus.REQUEST_SUCCEED) {
            val feedback = "亮度已设置为$brightness"
            onCommandExecuted?.invoke(true, feedback)
            sendTtsFeedback(feedback)
        } else {
            val feedback = "亮度设置失败，状态：$status"
            onCommandExecuted?.invoke(false, feedback)
            sendTtsFeedback(feedback)
        }
    }

    /**
     * 执行“关闭提词器”指令
     */
    private fun executeCloseWordTips() {
        val status = CxrApi.getInstance().controlScene(
            ValueUtil.CxrSceneType.WORD_TIPS,
            false,
            null
        )
        if (status == ValueUtil.CxrStatus.REQUEST_SUCCEED) {
            val feedback = "提词器已关闭"
            onCommandExecuted?.invoke(true, feedback)
            sendTtsFeedback(feedback)
        } else {
            val feedback = "提词器关闭失败，状态：$status"
            onCommandExecuted?.invoke(false, feedback)
            sendTtsFeedback(feedback)
        }
    }

    /**
     * 执行“拍照”指令
     */
    private fun executeTakePhoto() {
        val status = CxrApi.getInstance().controlScene(
            ValueUtil.CxrSceneType.WORD_TIPS,
            false,
            null
        )
        if (status == ValueUtil.CxrStatus.REQUEST_SUCCEED) {
            val feedback = "提词器已关闭"
            onCommandExecuted?.invoke(true, feedback)
            sendTtsFeedback(feedback)
        } else {
            val feedback = "提词器关闭失败，状态：$status"
            onCommandExecuted?.invoke(false, feedback)
            sendTtsFeedback(feedback)
        }
    }

    /**
     * 发送TTS反馈到眼镜端（由眼镜播放语音）
     */
    private fun sendTtsFeedback(feedbackText: String) {
        Log.d(TAG, "发送TTS反馈：$feedbackText")
        val status = CxrApi.getInstance().sendTtsContent(feedbackText)
        if (status != ValueUtil.CxrStatus.REQUEST_SUCCEED) {
            Log.e(TAG, "TTS反馈发送失败，状态：$status")
        } else {
            // 通知眼镜TTS播放结束（可选，根据业务需求）
            CxrApi.getInstance().notifyTtsAudioFinished()
        }
    }

    /**
     * 从ASR文本中提取亮度值（简单正则匹配）
     */
    private fun extractBrightness(asrText: String): Int? {
        val regex = Regex("亮度(为|设置为)?(\\d+)")
        val matchResult = regex.find(asrText)
        return matchResult?.groupValues?.get(2)?.toIntOrNull()
    }
}